package com.system.demo.utils;


import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;

/**
 * 类描述: 登录工具箱
 * @since 1.0
 * @author luodeng
 */
public class LoginUtils {



    /**
     * 对验证码生成图片
     *
     * @param captchaCode 验证码
     * @return 验证码图片
     */
    public static byte[] generateCaptchaImage(String captchaCode) {
        // 图片宽度和高度
        int width = 120;
        int height = 40;
        // 创建图像对象
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = image.createGraphics();

        // 设置背景色
        g2d.setColor(Color.WHITE);
        g2d.fillRect(0, 0, width, height);

        // 设置边框
        g2d.setColor(Color.LIGHT_GRAY);
        g2d.drawRect(0, 0, width - 1, height - 1);

        // 添加噪点
        Random random = new Random();
        for (int i = 0; i < 50; i++) {
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            g2d.drawOval(x, y, 1, 1);
        }

        // 添加干扰线
        for (int i = 0; i < 3; i++) {
            int x1 = random.nextInt(width);
            int y1 = random.nextInt(height);
            int x2 = random.nextInt(width);
            int y2 = random.nextInt(height);
            g2d.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
            g2d.drawLine(x1, y1, x2, y2);
        }

        // 绘制验证码
        g2d.setColor(Color.BLUE);
        g2d.setFont(new Font("Arial", Font.BOLD, 24));
        char[] chars = captchaCode.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            g2d.rotate(Math.toRadians(random.nextDouble() * 10 - 5), 20 * i + 15, 25);
            g2d.drawChars(chars, i, 1, 20 * i + 15, 25);
        }

        // 清理资源
        g2d.dispose();

        // 将图像转换为字节数组
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            ImageIO.write(image, "png", baos);
            return baos.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException("生成验证码图片失败", e);
        }
    }
    /**
     * 生成验证码
     *
     * @return 生成验证码
     */
    public static String generateCaptcha() {
        // 定义验证码字符集
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        // 验证码长度
        int length = 4;
        // 创建一个随机数生成器
        Random random = new Random();
        // 构建验证码字符串
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            sb.append(chars.charAt(random.nextInt(chars.length())));
        }
        return sb.toString();
    }


}
